package com.huatai.bi.utils;

import com.huatai.bi.utils.FilterComponent.FieldColumn;
import com.huatai.bi.utils.FilterComponent.Node;
import com.huatai.common.error.exception.ServiceException;
import org.springframework.util.CollectionUtils;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class FilterExp {

	StringBuffer buffer = new StringBuffer();
	StringBuffer fieldBuffer = new StringBuffer();
	Node node;
	Set<String> columns = new HashSet<>();
	String title;

	public FilterExp(Node node){
		this.node = node;
		if(null != node){
			expresse(this.node);
			if(fieldBuffer.length()>0){
				fieldBuffer.delete(fieldBuffer.length()-1,fieldBuffer.length());
			}
			if(buffer.length() > 0 ){
				buffer.insert(0,"(").append(")");
			}
		}
	}

	public FilterExp(Node node,String title,Set<String> columns){
		this.node = node;
		this.title = title;
		this.columns = columns;
		if(null != node){
			expresse(this.node);
			if(fieldBuffer.length()>0){
				fieldBuffer.delete(fieldBuffer.length()-1,fieldBuffer.length());
			}
			if(buffer.length() > 0 ){
				buffer.insert(0,"(").append(")");
			}
		}
	}
	public String exp(){
		return buffer.toString();
	}

	public String getFields(){
		return fieldBuffer.toString();
	}

	private int expresse(Node node){
		int type = 0;
		//子节点和字段都为空
		if(CollectionUtils.isEmpty(node.getFiedlList()) && CollectionUtils.isEmpty(node.getNodeList())){
			return type;
		}
		//先处理节点字段
		if(node.getFiedlList().size()>0){
			type++;
			List<FieldColumn> fiedlList = node.getFiedlList();
			for (int i = 0; i < fiedlList.size(); i++) {
				FieldColumn fieldColumn = fiedlList.get(i);
				if(columns.size() > 0 && !columns.contains(fieldColumn.getFieldName())){
					throw new ServiceException(String.format("组件 %s 配置的过滤字段 %s 不存在",title,fieldColumn.getLabel()));
				}
				if(i > 0){
					buffer.append(" ").append(node.getOperator());
				}
				buffer.append(" ").append(fieldColumn.getExp());
				fieldBuffer.append(fieldColumn.getFieldName()).append("、");
			}
		}
		//子节点
		if(node.getNodeList().size()>0){
			List<Node> nodeList = node.getNodeList();
			for (int i = 0; i < nodeList.size(); i++) {
				int index = buffer.length();
				if(type == 1){
					buffer.append(" ").append(node.getOperator());
				}
				int kuohaoIndex = buffer.length();
				int res = expresse(nodeList.get(i));
				if(0 == res){
					buffer.delete(index,buffer.length());
					return type;
				}else if(2 != res){
					buffer.insert(kuohaoIndex," (");
					buffer.append(")");
				}
			}
			type = type+2;
		}
		return type;
	}
}
